import React, { Component } from 'react'
import { Redirect, Route } from 'react-router-dom'
import { getUser } from 'utils'

export default class AuthRoute extends Component<any> {
  render() {
    const { component: Component, ...rest } = this.props
    return (
      <Route
        {...rest}
        render={(props) => {
          const withList = ['/login', '/404']
          const { pathname } = props.location

          const token = getUser()

          if (withList.includes(pathname)) {
            return <Component {...props} />
          }

          if (token) {
            return <Component {...props} />
          } else {
            return (
              <Redirect
                to={{
                  pathname: '/login',
                  state: {
                    fromPathname: pathname
                  }
                }}
              ></Redirect>
            )
          }
        }}
      />
    )
  }
}

// 使用
// import AuthRoute from './components/AuthRoute'
// <AuthRoute path="/home" component={Layout} />
// const { state } = this.props.location
//       if (state && state.formpath) {
//         this.props.history.push(state.formpath)
//       } else {
//         this.props.history.push('/home')
//       }
